﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Routing;

namespace mesoBoard.Web.Models
{
    public class Paging
    {
        public int CurrentPage { get; private set; }

        public int TotalPages { get; private set; }

        public string Controller { get; private set; }

        public string Action { get; private set; }

        public bool Shorten { get; private set; }

        public int Start { get; private set; }

        public int Stop { get; private set; }

        public RouteValueDictionary RouteOptions { get; private set; }

        private void Init(int CurrentPage, int TotalPages, string Action, string Controller, RouteValueDictionary RouteOptions = null)
        {
            this.CurrentPage = CurrentPage;
            this.TotalPages = TotalPages;
            this.Controller = Controller;
            this.Action = Action;
            if (RouteOptions == null)
                RouteOptions = new RouteValueDictionary();

            this.RouteOptions = RouteOptions;
            
            this.Shorten = this.TotalPages >= 10;

            this.Start = 2;
            this.Stop = this.TotalPages - 1;

            if (this.Shorten)
            {
                if (this.CurrentPage - 3 > 0) this.Start = this.CurrentPage - 2;
                if (this.Start == 3 && this.CurrentPage == 5) this.Start--;

                if (this.TotalPages - this.CurrentPage > 4) this.Stop = this.CurrentPage + 2;


                if (this.Start == 1) this.Start++;
                if (this.Stop == this.TotalPages || this.Stop > this.TotalPages) this.Stop = this.TotalPages - 1;

            }

            RouteOptions.Add("Page", 0);
        }

        public Paging(int CurrentPage, int TotalPages, string Action, string Controller, RouteValueDictionary RouteOptions=null)
        {
            this.Init(CurrentPage, TotalPages, Action, Controller, RouteOptions);
        }

        public Paging(int Count, int PageSize, int CurrentPage, string Action, string Controller, RouteValueDictionary RouteOptions = null)
        {
            this.Init(CurrentPage, (int)Math.Ceiling(((decimal)Count / PageSize)), Action, Controller, RouteOptions);
        }

        public RouteValueDictionary GetDictionary(int i)
        {
            this.RouteOptions["Page"] = i;
            return RouteOptions;
        }

    }
}
